package likou.dtgh;

import java.util.HashMap;
import java.util.Map;

/**
 * https://leetcode-cn.com/problems/arithmetic-slices-ii-subsequence/solution/gong-shui-san-xie-xiang-jie-ru-he-fen-xi-ykvk/
 */
public class _446 {
    public static void main(String[] args) {
        System.out.println(numberOfArithmeticSlices2(new int[]{7, 7, 7, 7, 7}));
    }

    public static int numberOfArithmeticSlices(int[] nums) {
        int len = nums.length;
        Map<Long, Integer>[] map = new Map[len];
        for (int i = len - 1; i >= 0; i--) {
            map[i] = new HashMap<>();
            for (int j = 0; j < i; j++) {
                map[i].merge((long) nums[i] - nums[j], 1, Integer::sum);
            }
        }
        int ans = 0;
        for (int i = 0; i < len; i++) {
            Map<Long, Integer> cur = map[i];
            for (Long key : cur.keySet()) ans += cur.get(key);
        }
        int a1 = 0, an = len - 1;
        int cnt = (a1 + an) * len / 2;
        return ans - cnt;
    }

    public static int numberOfArithmeticSlices2(int[] nums) {
        int ans = 0;
        int n = nums.length;
        Map<Long, Integer>[] f = new Map[n];
        for (int i = 0; i < n; ++i) {
            f[i] = new HashMap<>();
            for (int j = 0; j < i; ++j) {
                long d = (long) nums[i] - nums[j];
                int cnt = f[j].getOrDefault(d, 0);
                ans += cnt;
                f[i].put(d, f[i].getOrDefault(d, 0) + cnt + 1);
            }
        }
        return ans;
    }

}
